package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 面试评分模块表 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2024-11-28
 */
@Controller
@RestController
@RequestMapping("/api/gradeModule")
public class GradeModuleController extends BaseController{
    @Autowired
    IGradeModuleService iGradeModuleService;
    @Autowired
    IGradeDetailsService iGradeDetailsService;
    @Autowired
    IGradeOptionService iGradeOptionService;
    @Autowired
    IRecruitService iRecruitService;
    @Autowired
    IEstimateDetailsService iEstimateDetailsService;
    @Autowired
    IRecruitScreenSetService iRecruitScreenSetService;

    @Autowired
    ITryJobService iTryJobService;
    @Autowired
    ITrialFormService iTrialFormService;

    //查询模块
    @RequestMapping("/commentList")
    public Result commentList(@RequestParam(value ="type",defaultValue = "0") String type)  {
//        QueryWrapper<GradeModule>   queryWrapper= new QueryWrapper<>();
//        queryWrapper.eq("deleted",0);
////        queryWrapper.eq("type",type);
//
//
//        queryWrapper.eq("status",1);
//        queryWrapper.orderByAsc("sort");
//        List<GradeModule> list = iGradeModuleService.list(queryWrapper);
        List<GradeModule> list = iGradeModuleService.getGradeModuleByType( type);
        for (GradeModule gradeModule : list) {
            List<GradeDetails> gradeDetailsList = iGradeDetailsService.list(
                    new QueryWrapper<GradeDetails>()
                            .eq("grade_module_id", gradeModule.getId())
                            .eq("status",1)
                            .eq("pid",0)
                            .eq("deleted",0)
                            .orderByAsc("sort"));

            gradeModule.setGradeDetailsList(gradeDetailsList);
            for (GradeDetails gradeDetails1 : gradeDetailsList){
                List<GradeDetails> gradeDetails = iGradeDetailsService.list(
                        new QueryWrapper<GradeDetails>()
                                .eq("pid", gradeDetails1.getId())
                                .eq("status",1)
                                .eq("deleted",0)
                                .orderByAsc("sort"));

                for (GradeDetails gradeDetails2 : gradeDetails) {
                    List<GradeOption> gradeOptionList = iGradeOptionService.list(
                            new QueryWrapper<GradeOption>()
                                    .eq("grade_details_id", gradeDetails2.getId())
                                    .eq("status",1)
                                    .eq("deleted",0)
                                    .orderByAsc("sort"));
                    gradeDetails2.setGradeOptionList(gradeOptionList);
                }
                gradeDetails1.setGradeDetailsList(gradeDetails);
            }

        }

        return new Result(Code.GET_OK, list, Code.GET_OK_MSG);

    }


    /**
     * 人事升级后的接口
     * @param recruitId
     * @param type
     * @return
     */
    /******************调整中***********/
    @RequestMapping("/estimateDetail")
    public Result getModulesByEstimateAnswer(@RequestParam("recruitId") Long recruitId,
                                             @RequestParam("type") Integer type) {

        Recruit recruit = iRecruitService.getById(recruitId);
        if (recruit == null) {
            return new Result(Code.ERROR, "", "不存在该数据");
        }
        if (recruit.getScore() == null) {
            return new Result(Code.ERROR, "", "还未点评，请先提交评分");
        }

        // 构建子查询语句
        String estimateDetailsSubQuery = "SELECT grade_details_id FROM adms_estimate_details WHERE recruit_id = " + recruitId + " AND type = " + type;
        String parentIdSubQuery = "SELECT pid FROM adms_grade_details WHERE id IN (" + estimateDetailsSubQuery + ")";
        String moduleIdsSubQuery = "SELECT grade_module_id FROM adms_grade_details WHERE id IN (" + parentIdSubQuery + ")";

        // 查询符合条件的模块
        QueryWrapper<GradeModule> queryWrapper = new QueryWrapper<>();
        queryWrapper.inSql("id", moduleIdsSubQuery)
                .le("created_at", recruit.getEstimateTime())
                .orderByAsc("sort");

        List<GradeModule> list = iGradeModuleService.list(queryWrapper);

        // 加载完整结构（模块 -> 模块详情 -> 题目 -> 选项 -> 答案ID）
        for (GradeModule gradeModule : list) {
            List<GradeDetails> topLevelDetails = iGradeDetailsService.getGradeDetails(gradeModule.getId(), recruitId, type);
//            List<GradeDetails> topLevelDetails = iGradeDetailsService.list(
//                    new QueryWrapper<GradeDetails>()
//                            .eq("grade_module_id", gradeModule.getId())
//                            .eq("pid", 0)
//                            .orderByAsc("sort"));
            gradeModule.setGradeDetailsList(topLevelDetails);

            for (GradeDetails detail : topLevelDetails) {
                List<GradeDetails> subDetails = iGradeDetailsService.list(
                        new QueryWrapper<GradeDetails>()
                                .eq("pid", detail.getId())
                                .le("created_at", recruit.getEstimateTime())
//                                .eq("deleted", 0)
                                .orderByAsc("sort"));

                for (GradeDetails subDetail : subDetails) {
                    List<GradeOption> options = iGradeOptionService.list(
                            new QueryWrapper<GradeOption>()
                                    .eq("grade_details_id", subDetail.getId())
                                    .le("created_at", recruit.getEstimateTime())
//                                    .eq("deleted", 0)
                                    .orderByAsc("sort"));
                    subDetail.setGradeOptionList(options);

                    List<Long> estimateIds = iEstimateDetailsService.list(
                                    new QueryWrapper<EstimateDetails>()
                                            .eq("recruit_id", recruitId)
                                            .eq("type", type)
                                            .eq("grade_details_id", subDetail.getId()))
                            .stream().map(EstimateDetails::getOptionId).collect(Collectors.toList());
                    subDetail.setEstimateIds(estimateIds);
                }

                detail.setGradeDetailsList(subDetails);
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("score", recruit.getScore().toString());
        result.put("list", list);

        return new Result(Code.OK, result, Code.GET_OK_MSG);
    }


    /**
     * 人事升级后的接口
     * @param recruitId
     * @param type
     * @return
     */
/*    @RequestMapping("/estimateDetail")
    public Result estimateDetail(@RequestParam(value = "recruitId",required = true) Long recruitId,
                                 @RequestParam(value = "type",required = true) Integer type
    ) {

        Recruit recruit = iRecruitService.getById(recruitId);
        if (recruit==null){
            return new Result(Code.ERROR,"","不存在该数据");
        }
        if (recruit.getScore()==null){
            return new Result(Code.ERROR,"","还未点评，请先点评");

        }

        String estimateDetailsSubQuery = "SELECT grade_details_id FROM adms_estimate_details WHERE recruit_id = " + recruitId + " AND type = " + type;
        String gradeDetailsSubQuery = "SELECT grade_module_id FROM adms_grade_details WHERE id IN (" + estimateDetailsSubQuery + ")";
        QueryWrapper<GradeModule> queryWrapper = new QueryWrapper<>();
        queryWrapper.inSql("id", gradeDetailsSubQuery);
        queryWrapper.eq("deleted", 0);
        queryWrapper.le("created_at",recruit.getEstimateTime());
        queryWrapper.orderByAsc("sort");

        List<GradeModule> list = iGradeModuleService.list(queryWrapper);
        //map返回集合
        Map<String, Object> map = new HashMap<>();
        //模块
        for (GradeModule gradeModule : list) {
            List<GradeDetails> gradeDetailsList = iGradeDetailsService.list(
                    new QueryWrapper<GradeDetails>()
                            .eq("grade_module_id", gradeModule.getId())
                            .eq("status",1)
                            .eq("pid",0)
                            .eq("deleted",0)
                            .orderByAsc("sort"));

            gradeModule.setGradeDetailsList(gradeDetailsList);
            //模块详情
            for (GradeDetails gradeDetails1 : gradeDetailsList){

                List<GradeDetails> gradeDetails = iGradeDetailsService.list(
                        new QueryWrapper<GradeDetails>()
                                .eq("pid", gradeDetails1.getId())
                                .le("created_at",recruit.getEstimateTime())
                                .eq("deleted",0)
                                .orderByAsc("sort"));

                //题目
                for (GradeDetails gradeDetails2 : gradeDetails) {
                    List<GradeOption> gradeOptionList = iGradeOptionService.list(
                            new QueryWrapper<GradeOption>()
                                    .eq("grade_details_id", gradeDetails2.getId())
                                    .le("created_at",recruit.getEstimateTime())
                                    .eq("deleted",0)
                                    .orderByAsc("sort"));
                    gradeDetails2.setGradeOptionList(gradeOptionList);

                    List<Long> estimateIds = iEstimateDetailsService.list(
                                    new QueryWrapper<EstimateDetails>()
                                            .eq("recruit_id", recruitId).eq("type", type).eq("grade_details_id", gradeDetails2.getId()))
                            .stream().map(EstimateDetails::getOptionId).collect(Collectors.toList());
                    gradeDetails2.setEstimateIds(estimateIds);
                }
                gradeDetails1.setGradeDetailsList(gradeDetails);

            }
        }

        Integer score = recruit.getScore();
        //返回分数score和集合list
        map.put("score", score.toString());

        map.put("list", list);
        return new Result(Code.OK, map, Code.GET_OK_MSG);
    }*/

    //人事未升级前的接口
   /* @RequestMapping("/estimateDetail")
    public Result estimateDetail(@RequestParam(value = "recruitId",required = true) Long recruitId,
                                 @RequestParam(value = "type",required = true) Integer type
                                 ) {

        Recruit recruit = iRecruitService.getById(recruitId);
        if (recruit==null){
            return new Result(Code.ERROR,"","不存在该数据");
        }
        if (recruit.getScore()==null){
            return new Result(Code.ERROR,"","还未点评，请先点评");

        }
        QueryWrapper<GradeModule>   queryWrapper= new QueryWrapper<>();
        queryWrapper.eq("deleted",0);
        queryWrapper.le("created_at",recruit.getEstimateTime());
        queryWrapper.orderByAsc("sort");
        List<GradeModule> list = iGradeModuleService.list(queryWrapper);
        //map返回集合
        Map<String, Object> map = new HashMap<>();
        //模块
        for (GradeModule gradeModule : list) {
            List<GradeDetails> gradeDetailsList = iGradeDetailsService.list(
                    new QueryWrapper<GradeDetails>()
                            .eq("grade_module_id", gradeModule.getId())
                            .eq("status",1)
                            .eq("pid",0)
                            .eq("deleted",0)
                            .orderByAsc("sort"));

            gradeModule.setGradeDetailsList(gradeDetailsList);
            //模块详情
            for (GradeDetails gradeDetails1 : gradeDetailsList){

                List<GradeDetails> gradeDetails = iGradeDetailsService.list(
                        new QueryWrapper<GradeDetails>()
                                .eq("pid", gradeDetails1.getId())
                                .le("created_at",recruit.getEstimateTime())
                                .eq("deleted",0)
                                .orderByAsc("sort"));

                //题目
                for (GradeDetails gradeDetails2 : gradeDetails) {
                    List<GradeOption> gradeOptionList = iGradeOptionService.list(
                            new QueryWrapper<GradeOption>()
                                    .eq("grade_details_id", gradeDetails2.getId())
                                    .le("created_at",recruit.getEstimateTime())
                                    .eq("deleted",0)
                                    .orderByAsc("sort"));
                    gradeDetails2.setGradeOptionList(gradeOptionList);

                    List<Long> estimateIds = iEstimateDetailsService.list(
                                    new QueryWrapper<EstimateDetails>()
                                            .eq("recruit_id", recruitId).eq("type", type).eq("grade_details_id", gradeDetails2.getId()))
                            .stream().map(EstimateDetails::getOptionId).collect(Collectors.toList());
                    gradeDetails2.setEstimateIds(estimateIds);
                }
                gradeDetails1.setGradeDetailsList(gradeDetails);

            }
        }

        Integer score = recruit.getScore();
        //返回分数score和集合list
        map.put("score", score.toString());

        map.put("list", list);
        return new Result(Code.OK, map, Code.GET_OK_MSG);
    }
*/
    /**
     * 点评提交
     *
     */
    @PostMapping("/saveEstimateDetails")
    public Result estimate(@RequestBody List<EstimateDetails> estimateDetailList) {
        if (estimateDetailList == null || estimateDetailList.isEmpty()) {
            return new Result(Code.ERROR, "", "提交数据为空");
        }
        // 遍历并保存
        //累计加分数
        Integer totalScore = 0;
//        boolean save = false;
        boolean allSaved = true;
        Integer type = 0;
        for (EstimateDetails estimateDetails : estimateDetailList) {
            type = estimateDetails.getType();
            QueryWrapper<EstimateDetails> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("recruit_id", estimateDetails.getRecruitId());
            queryWrapper.eq("grade_details_id", estimateDetails.getGradeDetailsId());
            queryWrapper.eq("type", estimateDetails.getType());

            //只获取一条
            // 查询是否存在记录
            EstimateDetails existingDetails = iEstimateDetailsService.getOne(queryWrapper);

            estimateDetails.setEstimateId(this.adminId);
            Integer score = estimateDetails.getScore();
            //累计加分数
            totalScore += score;
            boolean saveOrUpdateResult;
            if (existingDetails != null){
                // 如果存在，则更新
                existingDetails.setScore(estimateDetails.getScore());
                existingDetails.setEstimateId(estimateDetails.getEstimateId());
                existingDetails.setOptionId(estimateDetails.getOptionId());

                saveOrUpdateResult = iEstimateDetailsService.updateById(existingDetails);
            }else {
                // 如果不存在，则保存
                //estimateDetails.setType(1); //1面试点评 2试岗点评
                saveOrUpdateResult = iEstimateDetailsService.save(estimateDetails);
            }
            if (!saveOrUpdateResult) {
                allSaved = false;
                break;
            }
        }
        // 批量加入数据库
//        boolean save = iEstimateDetailsService.saveBatch(estimateDetailList);
        if (allSaved){
            if (type.equals(1)){
                //面试点评
                Recruit recruit = iRecruitService.getById(estimateDetailList.get(0).getRecruitId());
                recruit.setScore(totalScore);
                recruit.setEstimateTime(LocalDateTime.now());
                recruit.setEstimateId(this.adminId);
                recruit.setIsComment(0);
                boolean update = iRecruitService.updateById(recruit);
                if (update){
                    return new Result(Code.OK,"","提交成功");
                }
            } else if (type.equals(2)) {
                //试岗点评
                QueryWrapper<TryJob> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("recruit_id", estimateDetailList.get(0).getRecruitId());
                TryJob tryJob = iTryJobService.getOne(queryWrapper);
                if (tryJob!=null){
                    tryJob.setCommentId(this.adminId);
                    iTryJobService.updateById(tryJob);
                }
                return new Result(Code.OK,"","提交成功");
            } else if (type.equals(3)) {
                QueryWrapper<TryJob> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("recruit_id", estimateDetailList.get(0).getRecruitId());
                TryJob tryJob = iTryJobService.getOne(queryWrapper);
                if (tryJob!=null){
                    //试用点评
                    QueryWrapper<TrialForm> queryWrapperTrialForm = new QueryWrapper<>();
                    queryWrapperTrialForm.eq("try_job_id", tryJob.getId());
                    TrialForm trialForm = iTrialFormService.getOne(queryWrapperTrialForm);
                    if (trialForm!=null){
                        trialForm.setCommentId(this.adminId);
                        iTrialFormService.updateById(trialForm);
                    }
                    return new Result(Code.OK,"","提交成功");
                }

            }
        }
        return new Result(Code.ERROR,"","提交失败");
    }


    /**
     * 点评提交
     *
     */
    //原先的

    /*@PostMapping("/saveEstimateDetails")
    public Result estimate(@RequestBody List<EstimateDetails> estimateDetailList) {
        if (estimateDetailList ==null && estimateDetailList.size()>0){
            return new Result(Code.ERROR,"","提交数据为空");
        }
        // 遍历并保存
        //累计加分数
        Integer totalScore = 0;
        for (EstimateDetails estimateDetails : estimateDetailList) {
            estimateDetails.setEstimateId(this.adminId);
            Integer score = estimateDetails.getScore();
            //累计加分数
            totalScore += score;
        }

        // 批量加入数据库
        boolean save = iEstimateDetailsService.saveBatch(estimateDetailList);
        if (save){
            QueryWrapper<RecruitScreenSet>  queryWrapper = new QueryWrapper<>();

            queryWrapper.eq("station_type", 1);
            queryWrapper.last("limit 1");
            RecruitScreenSet recruitScreenSet = iRecruitScreenSetService.getOne(queryWrapper);

            Integer passType = 2;
            if (recruitScreenSet!=null){
                if (totalScore >= recruitScreenSet.getEstimatePassScore()  ){
                    passType = 1;
                }
            }
            Recruit recruit = iRecruitService.getById(estimateDetailList.get(0).getRecruitId());
            recruit.setScore(totalScore);
            recruit.setEstimateTime(LocalDateTime.now());
            recruit.setEstimateId(this.adminId);
            recruit.setPassType(passType);
            boolean update = iRecruitService.updateById(recruit);
            if (update){
                return new Result(Code.OK,"","提交成功");
            }
        }
        return new Result(Code.ERROR,"","提交失败");

        }
*/


}





